// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:37
describe: 因子分析相关功能
*/

use crate::svc::base::{DataFrame, StyleConfig};
use serde_json::Value;
use std::collections::HashMap;

/// 显示特征收益
pub fn show_feature_returns(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("因子", crate::svc::base::DataType::String, false);
    result.add_column("收益", crate::svc::base::DataType::Number, true);
    result.add_column("标准差", crate::svc::base::DataType::Number, true);
    result.add_column("夏普比率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示因子分层
pub fn show_factor_layering(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("分层", crate::svc::base::DataType::String, false);
    result.add_column("平均收益", crate::svc::base::DataType::Number, true);
    result.add_column("标准差", crate::svc::base::DataType::Number, true);
    result.add_column("样本数", crate::svc::base::DataType::Number, false);
    
    result
}

/// 显示因子值分布
pub fn show_factor_value(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("因子值", crate::svc::base::DataType::Number, false);
    result.add_column("频次", crate::svc::base::DataType::Number, false);
    result.add_column("累计频次", crate::svc::base::DataType::Number, false);
    result.add_column("累计占比", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示事件收益
pub fn show_event_return(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("事件日", crate::svc::base::DataType::String, false);
    result.add_column("事件收益", crate::svc::base::DataType::Number, true);
    result.add_column("累计收益", crate::svc::base::DataType::Number, true);
    result.add_column("显著性", crate::svc::base::DataType::String, false);
    
    result
}

/// 显示事件特征
pub fn show_event_features(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("特征", crate::svc::base::DataType::String, false);
    result.add_column("事件前", crate::svc::base::DataType::Number, true);
    result.add_column("事件后", crate::svc::base::DataType::Number, true);
    result.add_column("变化", crate::svc::base::DataType::Number, true);
    result.add_column("P值", crate::svc::base::DataType::Number, true);
    
    result
}

/// 计算因子IC
pub fn calculate_factor_ic(factor_values: &[f64], returns: &[f64]) -> f64 {
    if factor_values.len() != returns.len() || factor_values.is_empty() {
        return 0.0;
    }
    
    // 计算排名相关性
    let factor_ranks = calculate_ranks(factor_values);
    let return_ranks = calculate_ranks(returns);
    
    calculate_pearson_correlation(&factor_ranks, &return_ranks)
}

/// 计算因子分层收益
pub fn calculate_factor_layered_returns(factor_values: &[f64], returns: &[f64], num_layers: usize) -> Vec<f64> {
    if factor_values.len() != returns.len() || factor_values.is_empty() {
        return vec![];
    }
    
    // 创建因子值和收益的配对
    let mut pairs: Vec<(f64, f64)> = factor_values.iter().zip(returns.iter())
        .map(|(&f, &r)| (f, r))
        .collect();
    
    // 按因子值排序
    pairs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
    
    let layer_size = pairs.len() / num_layers;
    let mut layer_returns = Vec::new();
    
    for i in 0..num_layers {
        let start = i * layer_size;
        let end = if i == num_layers - 1 {
            pairs.len()
        } else {
            (i + 1) * layer_size
        };
        
        let layer_avg_return = pairs[start..end].iter()
            .map(|(_, r)| r)
            .sum::<f64>() / (end - start) as f64;
        
        layer_returns.push(layer_avg_return);
    }
    
    layer_returns
}

/// 计算事件研究收益
pub fn calculate_event_study_returns(prices: &[f64], event_dates: &[usize], window: usize) -> Vec<Vec<f64>> {
    let mut event_returns = Vec::new();
    
    for &event_date in event_dates {
        if event_date >= window && event_date + window < prices.len() {
            let mut returns = Vec::new();
            
            // 计算事件窗口内的收益率
            for i in (event_date - window)..=(event_date + window) {
                if i > 0 {
                    let return_rate = (prices[i] - prices[i - 1]) / prices[i - 1];
                    returns.push(return_rate);
                }
            }
            
            event_returns.push(returns);
        }
    }
    
    event_returns
}

/// 计算因子值分布
pub fn calculate_factor_value_distribution(factor_values: &[f64], num_bins: usize) -> Vec<(f64, usize)> {
    if factor_values.is_empty() {
        return vec![];
    }
    
    let min_val = factor_values.iter().fold(f64::INFINITY, |a, &b| a.min(b));
    let max_val = factor_values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
    
    let bin_size = (max_val - min_val) / num_bins as f64;
    let mut bins = vec![0; num_bins];
    
    for &value in factor_values {
        let bin_index = ((value - min_val) / bin_size).floor() as usize;
        let bin_index = bin_index.min(num_bins - 1);
        bins[bin_index] += 1;
    }
    
    let mut distribution = Vec::new();
    for (i, &count) in bins.iter().enumerate() {
        let bin_start = min_val + i as f64 * bin_size;
        distribution.push((bin_start, count));
    }
    
    distribution
}

/// 计算排名
fn calculate_ranks(data: &[f64]) -> Vec<f64> {
    let mut indexed: Vec<(usize, f64)> = data.iter().enumerate().collect();
    indexed.sort_by(|a, b| a.1.partial_cmp(b.1).unwrap());
    
    let mut ranks = vec![0.0; data.len()];
    let mut current_rank = 1.0;
    let mut i = 0;
    
    while i < indexed.len() {
        let mut j = i;
        let current_value = indexed[i].1;
        
        // 处理相同值
        while j < indexed.len() && indexed[j].1 == current_value {
            j += 1;
        }
        
        // 计算平均排名
        let avg_rank = (current_rank + (j - 1) as f64) / 2.0;
        for k in i..j {
            ranks[indexed[k].0] = avg_rank;
        }
        
        current_rank = j as f64;
        i = j;
    }
    
    ranks
}

/// 计算皮尔逊相关系数
fn calculate_pearson_correlation(x: &[f64], y: &[f64]) -> f64 {
    if x.len() != y.len() || x.is_empty() {
        return 0.0;
    }
    
    let n = x.len() as f64;
    let sum_x: f64 = x.iter().sum();
    let sum_y: f64 = y.iter().sum();
    let sum_xy: f64 = x.iter().zip(y.iter()).map(|(a, b)| a * b).sum();
    let sum_x2: f64 = x.iter().map(|a| a * a).sum();
    let sum_y2: f64 = y.iter().map(|b| b * b).sum();
    
    let numerator = n * sum_xy - sum_x * sum_y;
    let denominator = ((n * sum_x2 - sum_x * sum_x) * (n * sum_y2 - sum_y * sum_y)).sqrt();
    
    if denominator > 0.0 {
        numerator / denominator
    } else {
        0.0
    }
} 